package com.zyplayer.doc.git.service;


import com.zyplayer.doc.git.utils.BaseUtils;
import com.zyplayer.doc.git.utils.FilesUtils;
import com.zyplayer.doc.git.utils.HTML2Md;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class HtmlConvertToMarkdownImpl {


    private static final String mdFileNameSuffix = ".md";

    //    匹配markdown文件中图片的正则表达式 ，元组1中为图片描述，元组2中为图片地址 ![描述信息](图片的真实地址)
    private static final String IMAGE_PATTERN = "!\\[(.*)\\]\\((.*?)\\)";
    private static final Pattern pattern = Pattern.compile(IMAGE_PATTERN);


    HtmlConvertToMarkdownImpl() {
    }


    /**
     * fileType: 编辑框类型 1=HTML 2=Markdown
     *
     * @return
     */
    public Boolean convertToMd(String storagePath, String fileName, String htmlStr, String baseUri, String charset, int fileType) {
        if (StringUtils.isBlank(storagePath)) {
            return false;
        }
        if (StringUtils.isBlank(fileName)) {
            fileName = BaseUtils.uuid2() + mdFileNameSuffix;
        }
        if (!fileName.contains(mdFileNameSuffix)) {
            fileName = fileName + mdFileNameSuffix;
        }
        if (StringUtils.isBlank(charset)) {
            charset = StandardCharsets.UTF_8.toString();
        }
        try {
            String markdownContent;
            if (fileType == 1) {
                markdownContent = HTML2Md.convertHtml(htmlStr, baseUri);
            } else {
                markdownContent = this.convertRelativeToAbsolutePaths(htmlStr, baseUri);
            }

            String markdownFilePath = storagePath + File.separator + fileName;
            FilesUtils.newFile(markdownFilePath, markdownContent, charset);
        } catch (IOException e) {
            log.error("html转markdown文件失败：{}", e.getMessage());
            return false;
        }
        return true;
    }


    private String convertRelativeToAbsolutePaths(String markdownContent, String baseUri) {
        Matcher matcher = pattern.matcher(markdownContent);

        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String tips = matcher.group(1);
            String relativePath = matcher.group(2);
            String absolutePath = baseUri + relativePath;
            matcher.appendReplacement(sb, "![" + tips + "](" + absolutePath + ")");
        }
        matcher.appendTail(sb);

        return sb.toString();
    }
}
